<template>
  <div>
    <Header>
      <div slot="title" class="header-title">登录</div>
      <div slot="left" class="header-left">
        <img src="@/assets/index/back.png" alt />
      </div>
    </Header>
    <div class="account-login">
      <div class="logo">
        <div>
          <img src="./img/logo.png" />
        </div>
      </div>
      <div class="account-form" v-if="activeName == 'accountLogin'">
        <van-form validate-first :show-error='false' validate-trigger='onSubmit'  @submit="onSubmit" ref="accountform">
          <van-field
            v-model="username"
            @blur="blur('username',username)"
            @input="change('username',username)"
            name="username"
            :error-message='usernameMsg'
            clearable
            placeholder="请输入账号或手机号码"
            :rules="[
              {
                required: true,
                validator: validateAccount,
                message: (value)=>{
                  if(!value){
                    return '请输入用户名'
                  }
                  if(!this.validateAccount(value)){
                    return '请输入正确的用户名'
                  }
                }
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="phone-ico" src="./img/phone-ico.png" />
            </template>
          </van-field>
          <van-field
            v-model="password"
            :type="passwordType"
            name="password"
            :error-message='passwordMsg'
            @blur="blur('password',password)"
            @input="change('password',password)"
            clearable
            placeholder="请输入密码"
            :rules="[
              {
                required: true,
                validator: validatePass,
                message: (value)=>{
                  if(!value){
                    return '请输入密码'
                  }
                  if(value.length<6){
                    return '长度6-20个字符之间'
                  }
                  if(this._str(value, value[0]) == value.length){
                    return '不能使用同一字符'
                  }
                  if(!this.validatePass(value)){
                    return '非法字符，请使用字母、数字的组合，6-20个字符'
                  }
                },
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="password-ico" src="./img/password-ico.png" />
            </template>
            <template
              class="password-field"
              slot="right-icon"
              name="right-icon"
            >
              <img
                class="password-right"
                :src="
                  passwordType === 'password'
                    ? require('./img/ico-guanbi.png')
                    : require('./img/ico-zhangkai.png')
                "
                @click="switchPasswordType"
              />
            </template>
          </van-field>
        </van-form>
      </div>
      <div class="fastLogin-form" v-if="activeName == 'fastLogin'">
        <van-form validate-first :show-error='false' validate-trigger='onSubmit' @submit="onSubmit" ref="fastLoginform">
          <van-field
            v-model="phoneNum"
            name="phoneNum"
            @blur="blur('phoneNum',phoneNum)"
            @input="change('phoneNum',phoneNum)"
            clearable
            placeholder="请输入手机号码"
            :rules="[
              {
                required: true,
                validator: validatePhone,
                message: (value)=>{
                  if(!value){
                    return '请输入手机号'
                  }
                  if(!this.validatePhone(value)){
                    return '请输入正确的手机号'
                  }
                }
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="phone-ico" src="./img/phone-ico.png" />
            </template>
          </van-field>
          <van-field
            v-model="codeNum"
            type="text"
            name="codeNum"
            clearable
            placeholder="请输入验证码"
            @blur="blur('codeNum',codeNum)"
            @input="change('codeNum',codeNum)"
            :rules="[
              {
                required: true,
                validator: validateCode,
                message: (value)=>{
                  if(!value){
                    return '请输入验证码'
                  }
                  if(!this.validateCode(value)){
                    return '请输入正确的验证码'
                  }
                }
              },
            ]"
          >
            <template slot="left-icon" name="left-icon">
              <img class="password-ico" src="./img/password-ico.png" />
            </template>
            <template
              class="password-field"
              slot="right-icon"
              name="right-icon"
            >
              <span
                class="password-span"
                @click="getCode('fastLoginform', 'phoneNum')"
                v-if="!countDown"
                >获取验证码</span
              >
              <span class="password-span" v-else
                >重新获取( {{ restTime }} s)</span
              >
            </template>
          </van-field>
        </van-form>
      </div>
      <div class="biaozhu">
        <p style="color: #205fc6" @click="organizaRegistr">立即注册</p>
        <p
          style="color: #bcbcbe"
          @click="retrieve"
          v-if="activeName == 'accountLogin'"
        >
          忘记密码？
        </p>
      </div>
      <div>
        <div style="margin: 25px">
          <van-button
            class="loginButton"
            round
            block
            type="default"
            @click="buttonClick"
            >登录</van-button
          >
        </div>
        <p class="kuaijie">
          <span @click="changeLogin">{{ activeName == "accountLogin" ? "手机号快捷登录" : "账号登录" }}</span>

        </p>
      </div>
      <p class="tiaoyue">
        同意遵守
        <span @click="goServe">《用户服务协议》</span>和
        <span @click="goServeYinsi">《用户隐私政策》</span>
      </p>
    </div>
    <div class="divider">
      <van-divider>你还可以用以下方式登录</van-divider>
    </div>
    <div class="other-login">
      <img @click="wxClick" src="./img/wechat.png" />
      <img @click="qqClick" src="./img/qq.png" />
    </div>
    <!-- 账户登录验证码 -->
    <Verify
      @success="userLogin"
      :captchaType="captchaType"
      :phone="phoneNum"
      :imgSize="{ width: '400px', height: '200px' }"
      @changeloginLoading="changeloginLoading"
      ref="loginVer"
    ></Verify>
    <!-- 快速滑块验证码 -->
    <Verify
      @success="sliderPassed"
      :captchaType="captchaType"
      @changeloginLoading="changeloginLoading"
      :phone="phoneNum"
      :imgSize="{ width: '400px', height: '200px' }"
      ref="captchaVer"
    ></Verify>
  </div>
</template>

<script>
import Header from "@/components/header.vue";
import { Form, Field, Button, Divider } from "vant";
import Verify from "./component/verifition/Verify";
import md5 from "js-md5";
import userInfo from "./index";
import {
  CODE_TYPE,
  BUSINESS_TYPE,
  RESET_TIME,
  QQLogin,
  WeChatLogin,
  wbLogin,
} from "./utils/constant";
import {
  getPhoneCodeAPI,
  userLoginAPI,
  fastLoginAPI,
  firstLoginAPI,
} from "./api/login";
import {
  warningMessage,
  successMessage,
  errorMessage,
  linkName,
  linkOpen,
} from "./utils/function";
export default {
  data() {
    return {
      activeName: "fastLogin", //登录方式 fastLogin  accountLogin
      passwordType: "password",
      username: "",
      usernameMsg:'',
      passwordMsg:'',
      password: "",
      phoneNum: undefined,
      codeNum: "",
      loginLoading: false,
      countDown: false,
      restTime: RESET_TIME,
      uuid: "",
      fromPath:1
    };
  },
  components: {
    Header,
    Verify,
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Divider.name]: Divider,
  },
  beforeRouteEnter(to, from, next) {
  next(vm=>{
      vm.fromPath = from;
  })
},
  methods: {

    blur(type,v){
      let me = this;
      if(v){
        let form = '';
        this.activeName == "fastLogin" ? form = 'fastLoginform' : form = 'accountform';
        switch (type) {
          case 'username':
            this.$refs[form].validate('username');
            break;
          case 'password':
            this.$refs[form].validate('password');
            break;
          case 'phoneNum':
            this.$refs[form].validate('phoneNum');
            break;
          case 'codeNum':
            this.$refs[form].validate('codeNum');
            break;
          default:
            break;
        }
      }
    },
    change(type,v){
      if(v){
        let form = '';
        let me = this;
        this.activeName == "fastLogin" ? form = 'fastLoginform' : form = 'accountform';
        switch (type) {
          case 'username':
            this.$refs[form].validate('username');
            break;
          case 'password':
            this.$refs[form].validate('password');
            break;
          case 'phoneNum':
            this.$refs[form].validate('phoneNum');
            break;
          case 'codeNum':
            this.$refs[form].validate('codeNum');
            break;
          default:
            break;
        }
      }
    },
    _str(value, n){
        var tmp = 0;
        for(var i = 0; i < value.length; i++){
            if(value.charAt(i) == n){    //charAt()方法可返回指定位置的字符
              tmp++;
              console.log(tmp);
            }
        }
        return tmp;
    },
    switchPasswordType() {
      this.passwordType == "password"
        ? (this.passwordType = "text")
        : (this.passwordType = "password");
    },
    changeLogin() {
      this.activeName =
        this.activeName == "fastLogin" ? "accountLogin" : "fastLogin";
        this.$nextTick(()=>{
          this.activeName == "accountLogin" ? this.$refs["accountform"].resetValidation() : this.$refs["fastLoginform"].resetValidation();
        })
    },
    buttonClick() {
      this.activeName == "fastLogin"
        ? this.$refs["fastLoginform"].submit()
        : this.$refs["accountform"].submit();
    },
    onSubmit() {
      this.activeName == "fastLogin" ? this.fastLogin() : this.accountLogin();
    },
    fastLogin() {},

    accountLogin() {
      if (this.loginLoading) return;
      this.loginLoading = true;
      this.$refs.loginVer.show();

    },
    userLogin(val) {
      let me = this;
      let { value, uuid } = val;
      let { username, password } = this;
      let form = {
        account: username,
        password: md5(password),
        captchaForm: {
          businessType: BUSINESS_TYPE["login"],
          type: CODE_TYPE["blockPuzzle"],
          phone: username,
          uuid,
          value,
        },
      };
      userLoginAPI(form).then(
        (res) => {
          if (res.data.code == 0) {
            let data = res.data.data;
            userInfo.sign(data);
            successMessage("登录成功！", () => {
              localStorage.setItem('y-token',data.loginVo.token)
              localStorage.setItem('level',data.member.level)
              if(this.fromPath.name == "password"){
                me.$router.push({ path: "/" });
              }else{
                this.$router.go(-1)

              }
            });
          } else {
            this.loginLoading = false;
            warningMessage(res.data.msg);
          }
        },
        (error) => {
          this.loginLoading = false;
        }
      );
    },
    getCode(refName, name) {
      if (!this.phoneNum) {
         warningMessage("请输入手机号");
         return;
      };
      this.$refs[refName].validate(name).then(
        (_) => {
          console.log("打开滑动验证码");
          this.$refs.captchaVer.show();
        },
        (errorMsg) => {
          // warningMessage("手机号输入错误！");
        }
      );
    },
    // 滑块验证码通过，获取短信验证码
    sliderPassed(val) {
      let { value } = val;
      let self = this;
      getPhoneCodeAPI(val).then((res) => {
        if (res.data.code == 0) {
          this.countDown = true;
          this.uuid = res.data.data.uuid;
          let timer = setInterval(() => {
            if (self.restTime == 0) {
              this.countDown = false;
              clearInterval(timer);
              self.restTime = RESET_TIME;
              return;
            } else {
              self.restTime--;
            }
          }, 1000);
        } else {
          warningMessage(res.data.msg);
        }
      });
    },
    fastLogin() {
      let me = this;
      if (!this.uuid) {
        warningMessage("请先获取验证码");
        return;
      }

      if (this.loginLoading) return;

      this.loginLoading = true;
      let { phoneNum, codeNum } = this;
      let form = {
        captchaForm: {
          phone: phoneNum,
          businessType: BUSINESS_TYPE["login"],
          type: CODE_TYPE["phone"],
          uuid: this.uuid,
          value: codeNum,
        },
      };
      fastLoginAPI(form).then(
        (res) => {
          if (res.data.code === 0) {
            let data = res.data.data;
            // canResetPassword: // 用户是否可以重置密码
            // isExsit 0 不存在   1存在
            userInfo.sign(data);
            if (data.loginVo && data.loginVo.isExsit == 0) {
              // 跳转重置密码
              me.$router.push({ path: "/login/setPassword" });
            } else {
              me.$router.push({ path: "/" });
            }
            localStorage.setItem('y-token',data.loginVo.token)
            localStorage.setItem('level',data.member.level)
          } else {
            this.loginLoading = false;
            warningMessage(res.data.msg);
          }
        },
        (error) => {
          this.loginLoading = false;
        }
      );
    },
    retrieve() {
      this.$router.push({ path: "/login/retrieve" });
    },
    organizaRegistr() {
      this.$router.push({ path: "/login/organizaRegistr" });
    },
    goServe() {
      this.$router.push({ path: "/login/agree" });
    },
    goServeYinsi() {
      this.$router.push({ path: "/login/agreeYinsi" });
    },
    wxClick() {
      window.location.href = WeChatLogin;
    },
    qqClick() {
      window.location.href = QQLogin;
    },
    validateAccount(value) {
      let reg = /^[a-zA-Z0-9_-]{5,20}$/;
      return reg.test(value);
    },
    validatePhone(value) {
      let reg = /^(13\d|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18\d|19[89])\d{8}$/;
      return reg.test(value);
    },
    validatePass(value) {
      let reg = /^(?=.*\d)[A-Za-z\d]{6,20}$/;
      let flag = reg.test(value);
      if(flag){
        flag = !(this._str(value, value[0]) == value.length)
      }
      return flag
    },
    validateCode(value) {
      let reg = /^(\d|\w){4}$/;
      return reg.test(value);
    },
    changeloginLoading() {
      this.loginLoading = false;
    },
  },
  mounted() {
    this.$route.query.phoneBinding == "true"
      ? (this.activeName = "accountLogin")
      : (this.activeName = "fastLogin");

    this.$nextTick(() => {
    })
  },

  created() {
    this.captchaType = CODE_TYPE["blockPuzzle"];
  },
};
</script>

<style lang="scss">
@import "./css/index.scss";

.account-login {
  width: 100%;
  margin-top: 82px;
  .logo {
    width: 100%;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 150px;
      height: 150px;
    }
  }
}

.biaozhu {
  height: 50px;
  box-sizing: border-box;
  width: 100%;
  padding: 10px 22px;
  display: flex;
  justify-content: space-between;
  p {
    font-size: 17px;
    font-weight: 400;
  }
}
.van-cell::after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 8px;
    bottom: 0;
    left: 8px;
    border-bottom: 1px solid #ebedf0;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
}
.loginButton {
  background-image: url("./img/denglu-but.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  color: #ffffff !important;
}

.divider {
  width: 100%;
  padding: 5px 22px;
  box-sizing: border-box;
}
.other-login {
  width: 100%;
  height: 75px;
  box-sizing: border-box;
  padding: 15px 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  img {
    width: 40px;
    height: 40px;
  }
}
</style>
